/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ivanbiz.service;

import com.ivanbiz.dao.GLAccountDAO;
import com.ivanbiz.dao.InvoiceDAO;
import com.ivanbiz.dao.PembayaranDAO;
import com.ivanbiz.dao.impl.GLAccountDAOImpl;
import com.ivanbiz.dao.impl.PembayaranDAOImpl;
import com.ivanbiz.model.GLAccount;
import com.ivanbiz.model.Invoice;
import com.ivanbiz.model.Pembayaran;
import com.ivanbiz.model.Pengguna;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.zkoss.util.media.Media;
import org.zkoss.zul.Textbox;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Comboitem;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Fileupload;
import org.zkoss.zul.Iframe;
import org.zkoss.zul.Image;
import org.zkoss.zul.Label;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

/**
 *
 * @author IW20149X
 */
public class PembayaranLainLainActionService extends SelectorComposer<Component> {

    InvoiceDAO invoiceDAO;
    GLAccountDAO gLAccountDAO;
    @Wire
    Combobox listInvoice;
    @Wire
    Datebox datePosting;
    @Wire
    Textbox transactionReference;
    @Wire
    Combobox listDebitur;
    @Wire
    Combobox listKreditur;
    @Wire
    Textbox jumlah;
    @Wire
    Textbox deskripsi;
    @Wire
    Label label;
    @Wire
    Image image;
    @Wire
    Window winPembayaranLainLainAction;
    @Wire
    Iframe ipdf;
    Pembayaran pembayaran;
    GLAccount glDebitur;
    GLAccount glKreditur;
    PembayaranDAO pembayaranDAO;
    SimpleDateFormat sdf;
    Media media;

    @Override
    public void doAfterCompose(Component comp) throws Exception {
        super.doAfterCompose(comp);
        sdf = new SimpleDateFormat("yyMMdd");
        pembayaranDAO = new PembayaranDAOImpl();
        gLAccountDAO = new GLAccountDAOImpl();
        transactionReference.setValue(getTransaksiReference());
        renderDebitur();
        renderKreditur();
        pembayaran = (Pembayaran) Executions.getCurrent().getArg().get("pembayaran");
        if (pembayaran != null) {
            listDebitur.setValue(pembayaran.getDebitBankAccount().getNameGL() + " A/C No. " + pembayaran.getDebitBankAccount().getNoGL());
            listKreditur.setValue(pembayaran.getKreditBankAccount().getNameGL() + " A/C No. " + pembayaran.getKreditBankAccount().getNoGL());
        }
    }

    @Listen("onClick=#simpan;")
    public void simpan() {
        if (pembayaran == null) {
            pembayaran = new Pembayaran();
        }        
        pembayaran.setDateCreated(new Date());
        pembayaran.setStatus("2");
        pembayaran.setPathImage(label.getValue().isEmpty() ? "" : Executions.getCurrent().getDesktop().getWebApp().getRealPath("/file") + "/" + transactionReference.getValue() + ".jpg");
        pembayaran.setTransactionReference(transactionReference.getValue());
        pembayaran.setDatePosting(datePosting.getValue());
        pembayaran.setDebitBankAccount((GLAccount) listDebitur.getSelectedItem().getValue());
        pembayaran.setKreditBankAccount((GLAccount) listKreditur.getSelectedItem().getValue());
        pembayaran.setJumlah(jumlah.getValue().isEmpty() ? (double) 0 : new Double(jumlah.getValue()));
        pembayaran.setDeskripsi(deskripsi.getValue());
//        validate(pembayaran);
    }

    private void validate(Pembayaran pembayaran) {
        if (pembayaran.getDatePosting() == null) {
            Messagebox.show("Date tidak boleh kosong");
        } else if (pembayaran.getDebitBankAccount() == null) {
            Messagebox.show("Debitur tidak boleh kosong");
        } else if (pembayaran.getKreditBankAccount() == null) {
            Messagebox.show("Kreditur tidak boleh null");
        } else if (pembayaran.getJumlah() == (double) 0) {
            Messagebox.show("Jumlah tidak boleh kosong");
        } else if (pembayaran.getDeskripsi().trim().isEmpty()) {
            Messagebox.show("Deskripsi tidak boleh kosong");
        } else {
            try {
                pembayaranDAO.saveOrUpdate(pembayaran);
                saveImage();
                winPembayaranLainLainAction.detach();
            } catch (Exception ex) {
                Logger.getLogger(PembayaranLainLainActionService.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private void renderUbahNoInvoice() {
        try {
            List<Invoice> loadInvoice = invoiceDAO.getDataByEquals("1");
            loadInvoice.add(0, pembayaran.getInvoice());
            for (Invoice invoice : loadInvoice) {
                Comboitem item = new Comboitem();
                item.setValue(invoice);
                item.setLabel(invoice.getNII());
                listInvoice.appendChild(item);
            }
        } catch (Exception ex) {
            Logger.getLogger(PembayaranLainLainActionService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private String getTransaksiReference() {
        String noTransaksi = null;
        Pengguna pengguna = (Pengguna) Sessions.getCurrent().getAttribute("pengguna");
        try {
            noTransaksi = pembayaranDAO.getLastNoTransaksi();
            if (!"".equals(noTransaksi)) {
                String[] splitNoTransaksi = noTransaksi.split("-");
                int count = Integer.parseInt(splitNoTransaksi[2]);
                count += 1;
                if (count > 99999) {
                    noTransaksi = sdf.format(new Date()) + "-PL" + pengguna.getKode() + "-" + String.format("%05d", 1);
                } else {
                    noTransaksi = sdf.format(new Date()) + "-PL" + pengguna.getKode() + "-" + String.format("%05d", count);
                }
            } else {
                noTransaksi = sdf.format(new Date()) + "-PL" + pengguna.getKode() + "-" + String.format("%05d", 1);
            }
        } catch (Exception ex) {
            Logger.getLogger(PembayaranLainLainActionService.class.getName()).log(Level.SEVERE, null, ex);
        }
        return noTransaksi;
    }

    private void renderDebitur() {
        try {
            listDebitur.getItems().clear();
            List<GLAccount> loadDebitur = gLAccountDAO.getDataByEquals(GLAccount.class, "groupACC", "Kreditur");
            for (GLAccount gLAccount : loadDebitur) {
                Comboitem item = new Comboitem();
                item.setValue(gLAccount);
                item.setLabel(gLAccount.getNameGL() + " A/C No. " + gLAccount.getNoGL());
                listDebitur.appendChild(item);
            }
        } catch (Exception ex) {
            Logger.getLogger(PembayaranLainLainActionService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void renderKreditur() {
        try {
            listKreditur.getItems().clear();
            List<GLAccount> loadKreditur = gLAccountDAO.getDataByEquals(GLAccount.class, "groupACC", "BiayaLain");
            for (GLAccount gLAccount : loadKreditur) {
                Comboitem item = new Comboitem();
                item.setValue(gLAccount);
                item.setLabel(gLAccount.getNameGL() + " A/C No. " + gLAccount.getNoGL());
                listKreditur.appendChild(item);
            }
        } catch (Exception ex) {
            Logger.getLogger(PembayaranLainLainActionService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Listen("onClick=#upload;")
    public void upload() throws FileNotFoundException, IOException {
        media = Fileupload.get();
        if (media instanceof org.zkoss.image.Image) {
            File file = new File(media.getName());
            label.setValue(file.getName());
            ipdf.setContent(media);
        } else if (media != null) {
            Messagebox.show("Not an image: " + media, "Error", Messagebox.OK, Messagebox.ERROR);
        }
    }

    private void saveImage() {
        OutputStream out = null;
        try {
            InputStream inputStream = media.getStreamData();
            out = new FileOutputStream(pembayaran.getPathImage());
            byte[] buf = new byte[1024];
            int len;
            while ((len = inputStream.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.close();
            inputStream.close();
        } catch (IOException ex) {
            Logger.getLogger(PembayaranLainLainActionService.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                out.close();
            } catch (IOException ex) {
                Logger.getLogger(PembayaranLainLainActionService.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
